<?php

namespace app\common\service\logistics;

use app\common\library\ApiException;
use app\common\model\ExpressCooperate;
use app\common\model\TerminalExpress;
use app\common\model\TerminalOrder;
use think\Cache;
use think\Request;

/**
 * 终端轨迹
 */
class Terminal
{

    /**
     * 上传终端
     * @param $params
     * @return bool
     */
    public function upload_terminal($params): bool
    {
        $map_api = new \MapApi();
        $res5 = $map_api->create_terminal($params["entity_id"],$params["entity_son_id"],"express",$params["title"]);
        if($res5["status"] != 0 || $res5["message"] != "OK"){
            write_log($res5["message"],"添加到终端失败");
            return false;
        }
        return true;
    }

    /**
     * 快递员轨迹上传
     * @param $express_info
     * @param $lat
     * @param $lnt
     * @return true
     */
    public function upload_express_track($express_info,$lat,$lnt): bool
    {

        $map_api = new \MapApi();
        $entity_id = $express_info["user_id"]."_".$express_info["id"];
        $express_location = Cache::get("express_".$entity_id);
        if($express_location){
            $location_info = explode(",",$express_location);
            //判断当前位置是否在40米范围内
            $range_num = distance($location_info[0],$location_info[1],$lat,$lnt);
            if($range_num < "0.015"){
                return true;
            }
        }
        $res = $map_api->create_track($entity_id,$lat,$lnt);
        if($res["status"] != 0 || $res["message"] != "OK"){
            write_log($res["message"],"轨迹上传失败!");
            return false;
        }
        Cache::set("express_".$entity_id,$lat.",".$lnt);
        //更新最新轨迹
        TerminalExpress::where("user_id",$express_info["user_id"])->update([
            "gettime"   =>time()-60,
            "location"  => sprintf("%s,%s",$lat,$lnt),
            "lnt"       => $lnt,
            "lat"       => $lat,
        ]);
        return true;
    }

    /**
     * 快递员搜索
     * @param $lat
     * @param $lnt
     * @param $page
     * @param $page_size
     * @return mixed
     * @throws ApiException
     */
    public function search_express($user_id,$lat,$lnt,$page,$page_size)
    {
        if(!$lat || !$lnt){
            throw new ApiException("参数有误");
        }
        $query_data = [
            "location"      => sprintf("%s,%s",$lat,$lnt),
            "radius"        => "3000",
            "entity_type"   => "express",
            "type"          => 1,
            "orderby"       => sprintf("_distance(%s,%s)",$lat,$lnt)
        ];

        $obj = new \MapApi();
        $r = $obj->search_terminal($query_data,$page,$page_size);
        if($r["status"] != 0 || $r["message"] != "OK"){
            throw new ApiException("附近没有人");
        }
        $express = new Express();
        $data = [];
        foreach($r["result"]["data"] as $k=>$v){
            $entity_id = explode(",",$v["entity_id"]);
            $express_info = $express->express_user_info($entity_id[0]);
            $v["last_location"]["range_num"] = distance($lat,$lnt,$v["last_location"]["lat"],$v["last_location"]["lng"]);
            $cooperate_num = ExpressCooperate::where("user_id",$user_id)->where("express_id",$express_info["id"])->value("num");
            $data[] = [
                "entity_id"     => $v["entity_id"],
                "entity_desc"   => $v["entity_desc"],
                "work_type"     => $express_info["work_type"],//快递员状态
                "entity_name"   => $express_info["username"],//名称
                "mobile"        => $express_info["mobile"],//手机号
                "express_id"    => $express_info["id"],
                "express_uid"   => $express_info["user_id"],
                "avatar"        => $express_info["avatar"],
                "comment_score" => $express_info['comment_score'],
                "order_num"     => $express_info['order_num'],
                "last_location" => $v["last_location"], // 位置
                'cooperate_num' => !empty($cooperate_num)?$cooperate_num:0
            ];
        }unset($v);
        return $data;
    }

    /**
     * 订单包裹搜索
     * @param $lat
     * @param $lnt
     * @param $page
     * @param $page_size
     * @return mixed
     * @throws ApiException
     */
    public function search_order($lat,$lnt,$page,$page_size)
    {
        if(!$lat || !$lnt){
            throw new ApiException("参数有误");
        }
        $query_data = [
            "location"      => sprintf("%s,%s",$lat,$lnt),
            "radius"        => "3000",
            "entity_type"   => "order",
            "type"          => 1,
            "orderby"       => sprintf("_distance(%s,%s)",$lat,$lnt)
        ];

        $obj = new \MapApi();
        $r = $obj->search_terminal($query_data,$page,$page_size);
        if($r["status"] != 0 || $r["message"] != "OK"){
            throw new ApiException("附近没有人");
        }
        $data = [];
        $order = new Order();
        foreach($r["result"]["data"] as $k=>$v){
            $entity_id = explode("|",$v["entity_id"]);
            $order_info = $order->user_detail(null,$entity_id[1]);
            if($order_info["goods_status"] == 0){
                if(isset($v["last_location"])){
                    $order_info["rangenum"] = distance($lat,$lnt,$v['last_location']["lat"],$v['last_location']["lng"]);
                }else{
                    $terminal_order = TerminalOrder::where("order_id",$order_info["oid"])->field("lat,lnt")->find();
                    $order_info["rangenum"] = distance($lat,$lnt,$terminal_order["lat"],$terminal_order["lnt"]);
                }
                $data[] = $order_info;
            }
        }
        return $data;
    }


    public function get_express($express_id)
    {
        return TerminalExpress::where('express_id',$express_id)->find();
    }
}